﻿#include "ArkKcxpWorker.h"

using namespace kd;
static std::string kdgp_packet = "KDGP000002680000021000000000KDGB{\"AppIP\":\"127.0.0.1\",\"AppMAC\":\"34-41-5D-C2-A4-D4\",\"AppName\":\"V3\",\"AppSign\":\"f82e6fa9918acf0f7cf539a44cb2e4f\",\"ApiName\":\"V3\",\"ApiVersion\":\"3.0\",\"Context\":\"1\",\"MsgType\":\"session_logon\",\"Protocol\":\"STD\",\"SendingTime\":\"2021-05-06 15:59:08.414\",\"Version\":\"2.0\"}JSTB{\"AppID\":\"KCBPCli\",\"AppSecret\":\"GJ38LH3RpWHuNNCxBkTFG/6lHmmKcHfRlCUPvWaKKKCow/Cxc9Za9ftvz6ihzMeOvuvG7bK6RbPD5J33dgD4cL74LdN4e59qowISzSRJkViASzXOfAzfHwmM9lVkPpwOWjeFI+4EpUydXcDIxJxepqKlAezV3leaWXs8SUWHYtA=\"}";

int main(int argc, char *argv[])
{
	char sz[] = "Hello, World!";
	std::cout << sz << std::endl;

	// 任意处置客户端及其输入和输出的自由
	auto worker_handle = [&](const std::pair<char*, size_t>& input
		, bool& keepalive
		, bool& sendto_other
		, ArkClient_t& client)
	{
		sendto_other = false;
		keepalive = KEEPALIVE_CONNECTION;

		// 检查是否需要重组报文
		char* presult = (char*)je_malloc(input.second);
		memcpy(presult, input.first, input.second);

		//size_t* plength = (size_t*)je_malloc(sizeof(size_t));
		//memcpy(plength, &input.second, sizeof(size_t));

		// 数据直接返回客户端
		if (ArkMinnerConf::ins()->echotcpable)
		{
			je_free(presult);
			return kdgp_packet;
		}

		// 数据置入生产者队列
		ArkKcxpWorker::ins()->DealWithPacket(client, presult, input.second);

		// 数据不处理返回为空
		return std::string("");
	};

	char xpConfigfile[PATH_MAX];
	getcwd(xpConfigfile, PATH_MAX - 1);
	strncat(xpConfigfile, "/ArkMinner.ini", PATH_MAX - strlen(xpConfigfile));

	// 初始化日志库
	LOG_INIT("logs", "ArkMinner", L_INFO);
	// 初始化XP API
	if (!XpBpHelper::InitalizeXpBp())
		return -1;

	// 初始本地配置
	ArkMinnerConf::ins()->init(xpConfigfile);

	if (0 == ArkMinnerConf::ins()->processmode)
	{
		// 初始本地服务
		ArkTcpServer::ins()->init(ArkMinnerConf::ins()->netaddr, ArkMinnerConf::ins()->netport);
		// 线程模型运行
		ArkTcpServer::ins()->run(worker_handle);

		XpBpHelper::UnInitalizeXpBp();
	}
	else
	{
		std::function<void(pthread_mutex_t*, size_t*)> process_handle = [&](pthread_mutex_t* mtx, size_t* data)
		{
			char xpConfigfile[PATH_MAX];
			getcwd(xpConfigfile, PATH_MAX - 1);
			strncat(xpConfigfile, "/ArkMinner.ini", PATH_MAX - strlen(xpConfigfile));

			// 初始化日志库
			LOG_INIT("logs", "ArkMinner", L_INFO);
			// 初始化XP API
			if (!XpBpHelper::InitalizeXpBp())
				return;

			// 初始本地配置
			ArkMinnerConf::ins()->init(xpConfigfile);

			// 初始本地服务
			ArkTcpServer::ins()->init(ArkMinnerConf::ins()->netaddr, ArkMinnerConf::ins()->netport);
			// 设置关闭回调
			ArkTcpServer::ins()->set_shutdown([&]() {
				// 多进程重载支持
				std::cout << "process " << getpid() << " exit.\n";
			});
			// 进程模型运行
			ArkTcpServer::ins()->run(worker_handle);

			XpBpHelper::UnInitalizeXpBp();
		};

		std::function<bool(int)> signed_refork = [&](int status) {
			return true;
		};

		ArkMultiProcess main_process;
		main_process.run(process_handle, signed_refork, ArkMinnerConf::ins()->processmode);
	}

	return 0;
}